var createError = require('http-errors');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/user');
const jwtConfig = require('./config/index').jwt;
var { expressjwt: jwt } = require("express-jwt");

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(fileUpload());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

 // 自定义 Token 验证（中间件）
  app.use(jwt({
    secret: jwtConfig.jwtSecret,
    algorithms: jwtConfig.algorithm
  }).unless({
    path: ['/','/login']
  }));
  
// 处理 POST 请求到 /upload 路径
app.post('/upload', (req, res) => {
  if (!req.files || Object.keys(req.files).length === 0) {
    return res.status(400).send('没有上传文件.');
  }

  // 从请求中获取自定义的文件名 formData 中的 filename
  const customFileName = req.body.filename;
  // 获取上传的文件，字段名为 "file"
  let uploadedFile = req.files.TestShark;

  // 使用 mv() 方法将文件移动到服务器上的某个位置（例如 'images' 文件夹）
  uploadedFile.mv(`./public/images/${customFileName}`, (err) => {
    if (err) {
      console.error('文件移动失败:', err);
      return res.status(500).send(err);
    }
    res.send({
      code: 200,
      msg: '文件上传成功',
      data: {
        FileURL: 'http://localhost:3000/images/' + customFileName
      }
    });
  });
});


app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  res.status(err.status || 500);
  res.send({
    code: err.status || 500,
    msg: err.message
  });
});

module.exports = app;
